package com.gaohe.interceptor;

import com.alibaba.fastjson.JSON;
import com.gaohe.common.R;
import com.gaohe.config.PathMatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.util.Enumeration;
import java.util.Iterator;

@Component //注意当前类必须受Spring容器控制
//定义拦截器类，实现HandlerInterceptor接口
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //        System.err.println("拦截器执行");
        HttpSession session = request.getSession();
        //  1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        //2、判断本次请求是否需要处理
        boolean check = PathMatcher.check(requestURI);
        //3、如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要处理",requestURI);
            return true;
        }

        //  4、判断登录状态，如果已登录，则直接放行
        if(session.getAttribute("username") != null){
            log.info(requestURI,"用户已登录，放行...");
            return true;
        }

        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.setStatus(401);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
